import React, {Component} from 'react';
import {Button, Modal} from 'antd';
import Lng from "../common/lng";


class AddModal extends Component {

    constructor(props) {
        super(props);
    }

    state = {
        loading: false,
        visible: false,
    }
    showModal = () => {
        this.setState({
            visible: true,
        });
    }

    getForm() {
        return this.refs["form"].getForm();
    }

    getContent() {
        return this.refs["form"];
    }

    handleOk = (e) => {
        const self = this;
        const callback = self.props.callback;
        const request = self.props.request;
        const validate = self.props.validate;
        e.preventDefault();
        this.getForm().validateFields((err, values) => {
            if (err) {

            } else {
                //自定义验证
                let pass = validate ? validate(values) : true;
                if (!pass) {
                    return;
                }

                this.setState({loading: true});
                request ? request(values, (data) => {
                    callback ? callback(data) : null;
                    self.hideModal();
                }).catch((err) => {
                    self.stopLoadding();
                }) : null;
            }
        });
    }

    stopLoadding() {
        this.setState({loading: false});
    }

    hideModal() {
        this.setState({loading: false, visible: false});
    }

    handleCancel = () => {
        this.setState({visible: false});
    }

    render() {
        const {visible, loading} = this.state;
        return (
            <Modal
                visible={visible}
                title={Lng.get("common.add", {name: this.props.titleName})}
                onOk={this.handleOk}
                onCancel={this.handleCancel}
                width={500}
                destroyOnClose={true}
                maskClosable={false}
                footer={[
                    <Button key="back" onClick={this.handleCancel}>{Lng.get("common.cancel", {name: ""})}</Button>,
                    <Button key="submit" type="primary" loading={loading} onClick={this.handleOk}>
                        {Lng.get("common.submit")}
                    </Button>
                ]}
            >
                <this.props.content ref={"form"}/>
            </Modal>
        );
    }
}

export default AddModal;